//
//  TMNetManager.m
//  TaskManager
//
//  Created by vip on 16/5/18.
//  Copyright © 2016年 M&H. All rights reserved.
//

#import "TMNetManager.h"
#import "GNRAPIConfig.h"

@implementation TMNetManager
{
@private
    //请求模型数据 一旦初始化 外部不可修改
    NSArray * _urlArray;

}
+(instancetype)sharedTheSingletion{
    static TMNetManager * manager = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        manager = [[[self class] alloc] init];
    });
    return manager;
}
//初始化时将plist文件中所有的请求模型读取出
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSArray * array = [GNRAPIConfig apiConfig];
        NSMutableArray * tmpArr = [NSMutableArray array];
        for (NSDictionary * dic in array) {
            TMNetRequestItem * model = [[TMNetRequestItem alloc]init];
            [model creatModelWithDic:dic];
            [tmpArr addObject:model];
        }
        _urlArray = [tmpArr copy];
    }
    return self;
}

- (TMNetRequestItem *)getRequestItemForName:(NSString *)name{
    TMNetRequestItem * model = nil;
    for (TMNetRequestItem * md in _urlArray) {
        if ([md.name isEqualToString:name]) {
            model  = [[TMNetRequestItem alloc]init];
            model.name = md.name;
            model.url = md.url;
            model.path = md.path;
            model.method=md.method;
            model.staticParamDic = md.staticParamDic;
            model.responseType = md.responseType;
            break;
        }
    }
    return model;
}

-(void)netForRequestName:(NSString *)name withParam:(TMNetBaseModel *)para forDataModel:(TMNetBaseModel *)dataModel completion:(void (^)(BOOL, TMNetError *))completion{
    //遍历出请求对象
    TMNetRequestItem * model = [self getRequestItemForName:name];
    
    if (model==nil) {
        TMNetError * error = [[TMNetError alloc]init];
        error.msg = [NSString stringWithFormat:@"没有配置此请求:%@",name];
        completion(NO,error);
        return;
    }
    
    //获取请求方法
    NSString * method = model.method;
    if([[method uppercaseString] isEqualToString:@"POST"]){
        NSString * urlStr = model.url;
        NSDictionary * dic = [para modelMappingToDictionary];
        NSMutableDictionary * paramStaticDic = [[NSMutableDictionary alloc]initWithDictionary:model.staticParamDic];
        for (NSString * key in dic) {
            //如果有则更新
            if (paramStaticDic[key]!=nil) {
                paramStaticDic[key]=dic[key];
            }else{
                //如果没有 则添加
                [paramStaticDic setObject:dic[key] forKey:key];
            }
        }
        //配置特殊参数
//        [self configSpecialParam:para requestItem:model paramStaticDic:paramStaticDic];
        
        AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.securityPolicy = [TMNetManager customSecurityPolicy];
        
        NSLog(@"url = %@", urlStr);
        
        [manager POST:urlStr parameters:paramStaticDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            TMNetHandleType type;
            if ([[model.responseType uppercaseString]isEqualToString:@"DATA"]) {
                type = TMNetHandleTypeData;
            }else if([[model.responseType uppercaseString]isEqualToString:@"XML"]){
                type = TMNetHandleTypeXML;
            }else{
                type = TMNetHandleTypeJSON;
            }
            [TMNetHandleInterface handleNetDataType:type withNetData:responseObject finish:^(NSDictionary *dataDic) {
                [dataModel creatModelWithDic:dataDic];
                completion(dataModel.code.integerValue==200,nil);
            }];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            TMNetError * err = [[TMNetError alloc]init];
            err.msg =[NSString stringWithFormat:@"服务器请求错误，错误码:%ld",(long)error.code];
            completion(NO,err);
        }];
    }else{
        TMNetError * error = [[ TMNetError alloc]init];
        error.msg = [NSString stringWithFormat:@"不支持的请求方法:%@：%@",name,model.method];
        completion(NO,error);
    }
}

////配置特殊情况的参数
//- (void)configSpecialParam:(TMNetBaseModel *)param requestItem:(TMNetRequestItem *)model paramStaticDic:(NSMutableDictionary *)paramStaticDic{
//    if ([model.name isEqualToString:@"Register"]||
//        [model.name isEqualToString:@"Forgot_login"]) {
//        [paramStaticDic setObject:param.code forKey:@"code"];
//    }else if ([model.name isEqualToString:@"Discount_use"]){
//        if ([param isKindOfClass:[GNRUseDiscountParam class]]) {
//            GNRUseDiscountParam * useParam = (GNRUseDiscountParam *)param;
//            [paramStaticDic removeObjectForKey:@"id_discount"];
//            [paramStaticDic setObject:useParam.id_discount?:@"" forKey:@"id"];
//        }
//    }
//}

//上传头像
- (void)uploadHead:(NSString *)imagePath withParam:(TMNetBaseModel *)para forDataModel:(TMNetBaseModel *)dataModel progress:(void (^)(double progress))progress completion:(void (^)(BOOL, TMNetError *))completion{
    if (!imagePath.length) {
        TMNetError * error = [TMNetError new];
        error.msg = @"图片路径为空";
        completion(NO,error);
        return;
    }
    
    TMNetRequestItem * item = [self getRequestItemForName:@"Update_Info"];
    NSDictionary * dic = [para modelMappingToDictionary];
    NSMutableDictionary * paramStaticDic = [[NSMutableDictionary alloc]initWithDictionary:item.staticParamDic];
    for (NSString * key in dic) {
        //如果有则更新
        if (paramStaticDic[key]!=nil) {
            paramStaticDic[key]=dic[key];
        }else{
            //如果没有 则添加
            [paramStaticDic setObject:dic[key] forKey:key];
        }
    }
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:item.url parameters:paramStaticDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath] name:@"head" fileName:@"head.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.securityPolicy = [TMNetManager customSecurityPolicy];
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      dispatch_async(dispatch_get_main_queue(), ^{
                          progress(uploadProgress.fractionCompleted);
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          TMNetError * err = [TMNetError new];
                          err.msg =[NSString stringWithFormat:@"服务器请求错误，错误码:%ld",error.code];
                          completion(NO,err);
                      } else {
                          TMNetHandleType type;
                          if ([[item.responseType uppercaseString]isEqualToString:@"DATA"]) {
                              type = TMNetHandleTypeData;
                          }else if([[item.responseType uppercaseString]isEqualToString:@"XML"]){
                              type = TMNetHandleTypeXML;
                          }else{
                              type = TMNetHandleTypeJSON;
                          }
                          [TMNetHandleInterface handleNetDataType:type withNetData:responseObject finish:^(NSDictionary *dataDic) {
                              [dataModel creatModelWithDic:dataDic];
                              completion(dataModel.code.integerValue==200,nil);
                          }];
                      }
                  }];
    
    [uploadTask resume];
}

- (void)postParam:(NSMutableDictionary *)param forDataModel:(TMNetBaseModel *)dataModel completion:(void (^)(BOOL, TMNetError *))completion{
    //遍历出请求对象
    NSString * apiName = @"Timing";
    TMNetRequestItem * model = [self getRequestItemForName:apiName];
    
    if (model==nil) {
        TMNetError * error = [[TMNetError alloc]init];
        error.msg = [NSString stringWithFormat:@"没有配置此请求"];
        completion(NO,error);
        return;
    }
    
    //获取请求方法
    NSString * urlStr = model.url;
    AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.securityPolicy = [TMNetManager customSecurityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:urlStr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        TMNetHandleType type;
        if ([[model.responseType uppercaseString]isEqualToString:@"DATA"]) {
            type = TMNetHandleTypeData;
        }else if([[model.responseType uppercaseString]isEqualToString:@"XML"]){
            type = TMNetHandleTypeXML;
        }else{
            type = TMNetHandleTypeJSON;
        }
        NSLog(@"data %@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
        [TMNetHandleInterface handleNetDataType:type withNetData:responseObject finish:^(NSDictionary *dataDic) {
            [dataModel creatModelWithDic:dataDic];
            completion(dataModel.code.integerValue==200,nil);
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        TMNetError * err = [[TMNetError alloc]init];
        err.msg =[NSString stringWithFormat:@"服务器请求错误，错误码:%@",error];
        completion(NO,err);
    }];
}

+ (AFSecurityPolicy*)customSecurityPolicy{
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    return securityPolicy;
}

-(BOOL)cheakApi:(NSString *)data{
    if ([data isEqualToString:@"10001"]) {
        return YES;
    }else{
        return NO;
    }
}

@end
